package com.lu.stochastic31.fragment;

import java.util.Date;
import java.util.Random;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Vibrator;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockListFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.lu.stochastic31.R;
import com.lu.stochastic31.activity.Preferences;
import com.lu.stochastic31.adapter.RandomDetailListAdapter;
import com.lu.stochastic31.content.SQLiteHelper;

public class RandomDetailFragment extends SherlockListFragment implements
		SensorEventListener {
	public static final String ARG_ITEM_NAME_INDEX = "name_index";

	private RandomDetailListAdapter randomDetailAdapter;
	private AlertDialog dialog;

	// 定义sensor管理器
	private SensorManager mSensorManager;
	// 震动
	private Vibrator vibrator;
	private DialogInterface.OnClickListener dialogAction = new DialogInterface.OnClickListener() {
		@Override
		public void onClick(DialogInterface dlg, int which) {// TODO
			switch (which) {
			case Dialog.BUTTON_NEGATIVE:// Bad
				break;
			case Dialog.BUTTON_NEUTRAL:// Good
				SQLiteHelper.getInstance(getSherlockActivity()).insertRandom(
						name_index, random);
				refreshViews();
				break;
			case Dialog.BUTTON_POSITIVE:// Okay
			default:
				break;
			}
		}
	};

	private Cursor cursor;
	private long name_index = 0;
	private String name = "Name";
	private String random;

	private Random rand = new Random(new Date().getTime());

	public RandomDetailFragment() {
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (getArguments() != null
				&& getArguments().containsKey(ARG_ITEM_NAME_INDEX)) {
			name_index = getArguments().getLong(ARG_ITEM_NAME_INDEX);
			name = SQLiteHelper.getInstance(getSherlockActivity()).getName(name_index);
			// TODO name_index无效情况的处理（负数、0等）

			cursor = SQLiteHelper.getInstance(getSherlockActivity()).getRandoms(
					name_index, !getRepeatFlag());
			if (cursor.getCount() == 0) {
				SQLiteHelper.getInstance(getSherlockActivity()).importFromFile(
						name_index);
				cursor = SQLiteHelper.getInstance(getSherlockActivity()).getRandoms(
						name_index, !getRepeatFlag());
			}

			dialog = new AlertDialog.Builder(getSherlockActivity()).setTitle(name)
					.setTitle(name)
					.setPositiveButton(R.string.dialog_ok, dialogAction)
					// .setNegativeButton(R.string.dialog_bad, dialogAction)
					.setNeutralButton(R.string.dialog_good, dialogAction)
					.create();

			mSensorManager = (SensorManager) getSherlockActivity().getSystemService(
					Context.SENSOR_SERVICE);// 获取传感器管理服务
			vibrator = (Vibrator) getSherlockActivity().getSystemService(
					Service.VIBRATOR_SERVICE);// 震动

			randomDetailAdapter = new RandomDetailListAdapter(getSherlockActivity(),
					cursor, false);
			setListAdapter(randomDetailAdapter);

			Toast.makeText(getSherlockActivity(), getText(R.string.toast_shake_phone),
					Toast.LENGTH_LONG).show();
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		refreshViews();
		// 加速度传感器
		mSensorManager.registerListener(this,
				mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
				// 还有SENSOR_DELAY_UI、SENSOR_DELAY_FASTEST、SENSOR_DELAY_GAME等，
				// 根据不同应用，需要的反应速率不同，具体根据实际情况设定
				SensorManager.SENSOR_DELAY_NORMAL);
	}

	@Override
	public void onStop() {
		mSensorManager.unregisterListener(this);
		super.onStop();
	}

	@Override
	public void onPause() {
		mSensorManager.unregisterListener(this);
		super.onPause();
	}

	@Override
	public void onDestroyView() {
		cursor.close();
		super.onDestroyView();
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_refresh:
			refreshViews();
			return true;
		case R.id.menu_run_random:
			runRandom();
			return true;
		case R.id.menu_preference:
			startActivity(new Intent(getSherlockActivity(), Preferences.class));
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		inflater.inflate(R.menu.menu_random_detail, menu);
		super.onCreateOptionsMenu(menu, inflater);
	}

	private boolean getRepeatFlag() {
		return getSherlockActivity().getSharedPreferences(Preferences.PREFS_NAME,
				Preferences.MODE_PRIVATE).getBoolean(
				getString(R.string.preference_can_repeat), true);
	}

	private void refreshViews() {
		Cursor c = randomDetailAdapter.getCursor();
		randomDetailAdapter.changeCursor(SQLiteHelper
				.getInstance(getSherlockActivity()).getRandoms(name_index,
						!getRepeatFlag()));
		randomDetailAdapter.notifyDataSetChanged();
		c.close();
	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		// TODO Auto-generated method stub
		// 当传感器精度改变时回调该方法，Do nothing.
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		int sensorType = event.sensor.getType();

		switch (sensorType) {
		case Sensor.TYPE_ACCELEROMETER:
			float[] values = event.values;// values[0]:X轴，values[1]：Y轴，values[2]：Z轴
			/*
			 * 因为一般正常情况下，任意轴数值最大就在9.8~10之间，只有在你突然摇动手机的时候，瞬时加速度才会突然增大或减少。
			 * 所以，经过实际测试，只需监听任一轴的加速度大于14的时候，改变你需要的设置就OK了~~~
			 */
			if ((Math.abs(values[0]) > 14 || Math.abs(values[1]) > 14 || Math
					.abs(values[2]) > 14)) {// 摇动手机后
				runRandom();
			}
			break;
		default:
			break;
		}
	}

	private void runRandom() {
		random = ((Cursor) randomDetailAdapter.getItem(rand
				.nextInt(randomDetailAdapter.getCount())))
				.getString(SQLiteHelper.randomColumn);
		dialog.setMessage(random);
		dialog.show();
		if (getSherlockActivity().getSharedPreferences(Preferences.PREFS_NAME,
				Preferences.MODE_PRIVATE).getBoolean(
				getString(R.string.preference_vibrate_after_random), true))
			vibrator.vibrate(500);// 得到随机结果后，伴随震动提示~~
	}
}
